const Koa = require('koa');
const app = new Koa();
const router = require('koa-router')();
const hbs = require('handlebars');
const fs = require('fs');
const EventEmitter = require('events');
const event = new EventEmitter();


function renderPagelet1() {
    return new Promise(function (reslove, reject) {
        fs.readFile('./view/pagelet1.hbs', 'utf-8', function(err, html) {
            if (err) {
                reject(err);
            }
            let htmlString = hbs.compile(html.toString())({message: '我是pagelet1'});
            setTimeout(function () {
                event.emit('writeHtml',{ id: '#pagelet1', html: htmlString});
                reslove(htmlString);
            }, 500)
        });
    });
}

function renderPagelet2() {
    return new Promise(function (reslove, reject) {
        fs.readFile('./view/pagelet2.hbs', 'utf-8', function(err, html) {
            if (err) {
                reject(err);
            }
            let htmlString = hbs.compile(html.toString())({time: Date.now()});
            setTimeout(function () {
                event.emit('writeHtml',{ id: '#pagelet2', html: htmlString});
                reslove(htmlString);
            }, 200)
        });
    });
}


function getPagelets () {
    return Promise.all([renderPagelet1(), renderPagelet2()]).then((res)=> {
        event.emit('wirteEnd');
    })
}




router.get('/demo', async (ctx, next) => {
    ctx.res.writeHead(200 , {'Content-Type': 'text/html;charset=utf-8'});
    ctx.res.write(hbs.compile(fs.readFileSync('./view/index.hbs', 'utf-8').toString())());
    event.on('writeHtml',(pagelet) => {
        ctx.res.write(
            '<script>setHTML("'+pagelet.id+'", "' + encodeURI(pagelet.html) + '")</script>'
        );
    });
    event.on('wirteEnd', () => {
        ctx.res.write('\n</body>\n</html>');
        ctx.res.end();
    });
    await getPagelets();
})

app.use(router.routes());

app.listen(3000);